<?php


namespace app\mweb\controller;


use app\admin\model\Staff as StaffModel;
use app\admin\model\Token;
use app\admin\model\UserList as user;
use app\common\Common;
use app\sys\service\GateCli;
use think\Db;
use think\facade\Env;
use think\facade\Validate;
use think\Request;
use wechatcom\WechatComment;
use wework\WeWork;

class Staff extends Common
{
    // 企业微信与客服人员绑定
    public function bingQyeStaff(Request $request)
    {
        $data = $request->param();
        $validate = Validate::make([
            "code|code码"=>"require",
            "user|账号" => "require",
            "password|密码" => "require",
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }

        list($status,$msg) = StaffModel::login($data["user"],$data["password"]);
        if ($status == false){
            // 验证
            return failedJson("登录：{$msg}");
        }

//        $res = staffModel::ifWxBing($msg["StaffNumber"]);
//        if ($res) {
//            return failedJson("已经绑定成功~");
//        }
        // code 验证
//        $corpId = Env::get("QYE.CORPID");
//        $secret = Env::get("QYE.APP_SECRET");
//        $we = new WeWork($corpId,$secret);

        $corpId = Env::get("WXF.APP_ID");
        $secret = Env::get("WXF.APP_SE");
        $we = new WechatComment($corpId,$secret);

        $request->_user = "";
        $resData = array();
        // 启动事务
        Db::startTrans();
        try {
            list($useId,$dep) = $we->getUserInfoByCode($data["code"]);
            if($useId == "err"){
                return failedJson($dep);
            }
//            $msg["qye_user_id"] = $useId;
            $msg["fwx_user_id"] = $useId;
            // 是否绑定
//            $res = StaffModel::ifBing($msg["StaffNumber"]);

            // 数据添加
            $res = StaffModel::add($msg);
            if (!$res) {
                Db::rollback();
                return failedJson("绑定失败");
            }

            $resData["id"] = $res["id"];
            $resData["staff_no"] = $res["staff_no"];
            $resData["staff_name"] = $res["staff_name"];
            $resData["mobile"] = $res["mobile"];
            $resData["token"] = $msg["Token"];
            $resData["expire_time"] = strtotime($msg["ExpireTime"]);
            $resData["icon"] = $res["icon"];
            $resData["sex"] = $res["sex"];

            $token = Token::SaveToken($msg);
            if (!$token) {
                Db::rollback();
                return failedJson("绑定失败");
            }
            $request->_user = $res;
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return failedJson("绑定失败或重新到微信跳转",1,$e->getMessage());
        }
        return successJson("success",$resData);
    }

    // 用户列表
    public function userList(Request $request)
    {
        $data = $request->param();
        $validate = Validate::make([
            "user_type|会员类型" => "require",
        ]);

        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $search = $request->param("search", "");
        $userType = $request->param("user_type", 0);
        $page = $request->param("page", 0);
        $limit = $request->param("limit", 10);

        $staffInfo = $request->_user;
        $list = user::userLists($staffInfo["id"], $userType, $search,0, $page, $limit);
        return successJson("success", $list);
    }

    // 客户对接
    public function toStaff(Request $request)
    {
        $data = $request->param();
        $validate = Validate::make([
            "chat_id|聊天id" => "require",
            "to_staff_no|负责客服编号" => "require"
        ]);
        if (!$validate->check($data)) {
            return failedJson($validate->getError());
        }
        $staffInfo = $request->_user;

        $res = \app\admin\model\Staff::toStaff($data["chat_id"],$data["to_staff_no"],$staffInfo["staff_no"],$staffInfo["device_id"]);
        if ($res) return failedJson($res);
        return successJson("success","成功");
    }

    //修改状态
    public function staffStatus(Request $request)
    {
        $status = $request->param("status");
        $staffInfo = $request->_user;
        $resStaff = \app\admin\model\Staff::where("staff_no",$staffInfo["staff_no"])->find();
        if($resStaff["status"] == $status){
            return failedJson("状态相同~");
        }
        $res = \app\admin\model\Staff::where("staff_no",$staffInfo["staff_no"])
            ->data(["status"=>$status])->update();
        if(!$res)return failedJson("添加失败");
        return successJson("success","成功");
    }

    // 客服消息
    public function staffNews(Request $request)
    {
        $staffInfo = $request->_user;
        $info = user::staffNews($staffInfo["id"]);
        if (!$info) {
            return failedJson("未找到改客服~");
        }
        return successJson("success", $info);
    }
}